from django.http import HttpResponse
from datetime import datetime
from django.conf import settings
from os import path
import os
import json

def upload_image(request):
    """  """
    if request.method == 'POST':
        callback=request.GET.get('CKEditorFuncNum')
        f= request.FILES['upload']
        
        file_dir= path.join(settings.MEDIA_ROOT,'userdata',request.user.username,'image')
        try:
            os.makedirs(file_dir)
        except os.error as e:
            print(e)
        file_name=datetime.now().strftime('%Y%m%d%H%M%S')+f.name
        file_path=path.join(file_dir,file_name)
        handle_uploaded_file(f,file_path)
        file_url='/media/userdata/{user}/image/{file_name}'.format(user=request.user.username,file_name=file_name)
        if callback:
            return HttpResponse("""
            <script type="text/javascript">
            window.parent.CKEDITOR.tools.callFunction({callback},'{img_url}')
            </script>
            """.format(callback=callback,img_url=file_url))
        else:
            dc={"uploaded": 1,
                "fileName": f.name,
                'url':file_url
            }
            return HttpResponse(json.dumps(dc),content_type="application/json")
        
    
    
def handle_uploaded_file(f,file_path):
    with open( file_path, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)